<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <h1>按下鼠标或者触摸屏幕开始画画吧</h1>
  <kbd></kbd>
  <canvas id="canvas"></canvas>
  <script>
    let canvas = document.getElementById('canvas');
    let ctx = canvas.getContext('2d');
    let isTouchDevice = 'ontouchstart' in document.documentElement
    let painting = false;
    let last, history
    canvas.width = document.documentElement.clientWidth
    canvas.height = document.documentElement.clientHeight
    ctx.fillStyle = "red"
    ctx.strokeStyle = "red"
    ctx.lineWidth = 10
    ctx.lineCap = "round";

    if (isTouchDevice) {
      canvas.ontouchstart = (e) => {
        let x = e.touches[0].clientX
        let y = e.touches[0].clientY
        last = [x, y]
        e.preventDefault()
      }
      canvas.ontouchmove = (e) => {
        let x = e.touches[0].clientX
        let y = e.touches[0].clientY
        drawLine(last[0], last[1], x, y)
        last = [x, y]
        e.preventDefault()
      }
    } else {
      canvas.onmousedown = (e) => {
        let x = e.clientX
        let y = e.clientY
        painting = true;
        drawReact(x,y)
        last = [e.clientX, e.clientY]
      }
      canvas.onmouseup = (e) => {
        painting = false;
      }
      canvas.onmousemove = (e) => {
        if (painting) {
          let x = e.clientX
          let y = e.clientY
          drawLine(last[0], last[1], x, y)
          last = [x, y]
        }
      }
    }
    function drawReact(x, y) {
      ctx.beginPath()
      ctx.arc(x , y , 0,ctx.lineWidth / 2, 2 * Math.PI)
      ctx.stroke();
    }
    function drawLine(x1, y1, x2, y2) {
      ctx.beginPath()
      ctx.moveTo(x1, y1)
      ctx.lineTo(x2, y2)
      ctx.stroke();
    }

  </script>
</body>

</html>